import os

from PyQt6 import uic
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QWidget, QFileDialog, QMessageBox
import json

from utils.error import getError
from utils.index import resource_path


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.history_path = None
        self.ui = uic.loadUi(resource_path("static/ui/historyPath.ui"), self)  # 加载 UI 文件
        self.init_style()
        self.init_event()

    # ========================================================
    # 初始化
    # ========================================================

    # 初始化样式
    def init_style(self):
        self.ui.setWindowTitle("SeismicPlot-历史记录")
        self.ui.setWindowIcon(QIcon('static/image/favicon.ico'))

    # 初始化事件
    def init_event(self):
        self.ui.toolButton.clicked.connect(self.select_directory)
        # 连接按钮的点击事件
        self.ui.buttonBox.accepted.connect(self.accept_action)
        self.ui.buttonBox.rejected.connect(self.reject_action)

    # ========================================================
    # 工具函数
    # ========================================================

    # 目录选择框
    def select_directory(self):
        directory = QFileDialog.getExistingDirectory(self, '选择目录', '', QFileDialog.Option.ShowDirsOnly)
        if directory:
            self.history_path = directory
            self.ui.lineEdit.setText(directory)

    # Ok
    def accept_action(self):
        directory = self.ui.lineEdit.text()
        if not directory:  # 如果目录为空，弹出目录选择框
            self.select_directory()
        else:
            file_path = self.ui.lineEdit.text() + "/historyList.json"
            if os.path.exists(file_path):
                result = QMessageBox.question(None, '设置-保存历史记录的目录',
                                              '该目录已存在保存历史记录的文件，是否读取该目录下的历史记录文件？',
                                              QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.No | QMessageBox.StandardButton.Cancel)
                if result == QMessageBox.StandardButton.No:  # 覆盖原来的文件
                    self.update_hisotry_path()
                elif result == QMessageBox.StandardButton.Ok:  # 读取旧历史记录
                    # 关闭弹窗
                    self.ui.close()
                    # 修改setting.json中记录的历史记录文件的路径
                    with open(resource_path("static/json/setting.json"), 'r', encoding='utf-8') as file:
                        data = json.load(file)
                    data["history_path"] = file_path
                    with open(resource_path("static/json/setting.json"), 'w', encoding='utf-8') as file:
                        json.dump(data, file, indent=4)
                    QMessageBox.information(None, '操作成功', '保存历史记录文件的目录修改成功！',
                                            QMessageBox.StandardButton.Ok)
                elif result == QMessageBox.StandardButton.Cancel:  # 不进行任何操作
                    pass

    # 更新存放历史记录的路径
    def update_hisotry_path(self):
        data_list = {
            "bridge": [],
            "mul_wave": [],
            "layered": [],
            "joint_well": []
        }
        path = self.ui.lineEdit.text() + "/historyList.json"
        try:
            # 重新生成历史记录文件
            with open(path, 'w', encoding='utf-8') as file:
                json.dump(data_list, file, indent=4)
            # 关闭弹窗
            self.ui.close()
            # 修改setting.json中记录的历史记录文件的路径
            with open(resource_path("static/json/setting.json"), 'r', encoding='utf-8') as file:
                data = json.load(file)
            data["history_path"] = path
            with open(resource_path("static/json/setting.json"), 'w', encoding='utf-8') as file:
                json.dump(data, file, indent=4)
            QMessageBox.information(None, '操作成功', '成功覆盖原文件！', QMessageBox.StandardButton.Ok)
        except:
            err = getError()
            QMessageBox.critical(None, f"{err['type']}", f"{err['msg']}", QMessageBox.StandardButton.Ok)

    # CanCel
    def reject_action(self):
        self.ui.close()
